package com.zzn.bookManage.controller;

import com.zzn.bookManage.pojo.User;
import com.zzn.bookManage.service.UserService;
import com.zzn.bookManage.util.ObjectHolder;
import com.zzn.bookManage.util.StringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 用户登录
 */

@WebServlet("/userLogin")
public class UserLogin extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession(true); // 必定获得一个session

        String username = req.getParameter("lusername");
        String password = req.getParameter("lpassword");

        if (StringUtil.isBlank(username)){
            req.setAttribute("msg","用户名不能为空");
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
            return;
        }
        if (StringUtil.isBlank(password)){
            req.setAttribute("msg","密码不能为空");
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
            return;
        }

        UserService userService = ObjectHolder.getInstance().getUserService();
        User userIn = new User();
        userIn.setUsername(username);
        userIn.setPassword(password);
        User userOut = userService.loginUser(userIn);
        if (userOut==null){
            req.setAttribute("msg","用户名或密码不正确");
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
        }else{
            //登录成功后进入主页
            session.setAttribute("loginUser",userOut);
            resp.sendRedirect("/list?page=1");
        }
    }
}
